﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace Trig_AMJ_HR_Forms
{
    public class ExceptionHandler
    {

        #region Global Variables

        string strListName = "Exception Logs";
        string FormsSiteCollUrl = SPContext.Current.Site.Url + "/sites/forms";

        #endregion

        #region Custom Methods

        /// <summary>
        /// GenerateExceptionLog method, which validate whether "Exception Logs" list exists in site, if exists take list object and log the exception
        /// </summary>
        /// <param name="strTitle">Error Title</param>
        /// <param name="strErrMsg">Error Message</param>
        /// <param name="strDesc">Error Description</param>
        public void GenerateExceptionLog(string strTitle, string strErrMsg, string strDesc)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite osite = new SPSite(FormsSiteCollUrl))
                    {
                        using (SPWeb oWeb = osite.OpenWeb())
                        {
                            SPList oList = oWeb.Lists.TryGetList(strListName);
                            if (oList != null)
                            {
                                AcceptException(oList, strTitle, strErrMsg, strDesc);
                            }
                            else
                            {
                                if (CreateList(oWeb))
                                {
                                    oList = oWeb.Lists.TryGetList(strListName);
                                    AcceptException(oList, strTitle, strErrMsg, strDesc);
                                }
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// Creates a new custom list called "Exception Logs" along with fields "ErrorMsg" and "Description"
        /// </summary>
        /// <param name="oWeb">passing web from parent method</param>
        /// <returns>return list creation result (true/false)</returns>
        private bool CreateList(SPWeb oWeb)
        {
            bool rval = false;
            try
            {
                oWeb.AllowUnsafeUpdates = true;
                oWeb.Lists.Add(strListName, "Custom list to save exceptions", SPListTemplateType.GenericList);
                SPList olist = oWeb.Lists.TryGetList(strListName);
                olist.Fields.Add("ErrorMsg", SPFieldType.Note, true);
                olist.Fields.Add("Description", SPFieldType.Note, true);
                SPView view = olist.DefaultView;
                view.ViewFields.Add("ErrorMsg");
                view.ViewFields.Add("Description");
                view.ViewFields.Add("Modified");
                view.Query = "<OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy>";
                view.Update();
                olist.Update();
                oWeb.AllowUnsafeUpdates = false;
                rval = true;
            }
            catch (Exception ex)
            {
                rval = false;
            }
            return rval;
        }

        /// <summary>
        /// Update exception details in Exception Logs list
        /// </summary>
        /// <param name="oList">Exception Logs list object</param>
        /// <param name="strTitle">Error Title</param>
        /// <param name="strErrMsg">Error Message</param>
        /// <param name="strDesc">Error Description</param>
        private void AcceptException(SPList oList, string strTitle, string strErrMsg, string strDesc)
        {
            try
            {
                if (oList != null)
                {
                    SPQuery oEmptyQuery = new SPQuery();
                    oEmptyQuery.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Eq></Where>";
                    SPListItemCollection oItemColl = oList.GetItems(oEmptyQuery);
                    SPListItem oItem = oItemColl.Add();
                    oItem["Title"] = strTitle;
                    oItem["ErrorMsg"] = strErrMsg;
                    oItem["Description"] = strDesc;
                    oList.ParentWeb.AllowUnsafeUpdates = true;
                    oItem.Update();
                    oList.ParentWeb.AllowUnsafeUpdates = false;
                }
            }
            catch (Exception)
            {

            }
        }

        #endregion
    }
}
